package com.example.secondassignment;

import com.example.secondassignment.R;
import com.example.secondassignment.AlarmService.AlarmBinder;

import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.Dialog;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.text.format.Time;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class AlarmClock extends Activity {
	
	public static final int TimePicker = 0;
	private static AlarmService mService;
	private Activity main_activity;
	private TextView clock_display;
	private Handler handler = new Handler();
	private TimePicker inputTime;
	private TextView alarm;
    private boolean keepCounting;
    private int hour;
    private int minutes;
    private int seconds;
	private Time time;
	
	private static boolean alarmON = false;
	
	private PendingIntent alarmIntent; 
	private AlarmManager am;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.alarmclock_activity);
				
		main_activity = this;
		
		alarm = (TextView)findViewById(R.id.nextAlarm);
		

		setUpClock();
		setUpTimePicker(this);
		setUpButtons();
		setUpAlarmServiceConnection();
		setUpAlarm();
		
		System.out.println("onCreate...");
		
	}
		
	@Override
	protected void onResume(){
		
		System.out.println("onResume...");
		
		StartClock();
		if( !isAlarmON() ){
			alarm.setText("Alarm will go off: ");
		}

		super.onResume();
	}
	
	@Override
	protected void onPause(){

		super.onPause();
	}
	@Override
	protected void onDestroy(){
		
		unbindService(mConnection);
		StopClock();
       
		super.onDestroy();
	}
	
	private void setUpAlarm(){
		
		Intent intent = new Intent("com.example.secondassignment.ALARM_BROADCAST");
		intent.putExtra("message", "Test");
		
		alarmIntent = PendingIntent.getBroadcast(AlarmClock.this, 0, intent, 0);
		am = (AlarmManager)getSystemService(ALARM_SERVICE);
		
	}
	
	private void setUpClock(){
		time = new Time();
		
		clock_display = (TextView)findViewById(R.id.clockDisplay);
	}
	
	private void setUpAlarmServiceConnection(){
		Intent playAlarmSoundIntent = new Intent(main_activity,AlarmService.class);
		bindService(playAlarmSoundIntent, mConnection, main_activity.BIND_AUTO_CREATE);
	}
	
	private void setUpTimePicker(Context context){
		inputTime = new TimePicker(context);
	}
	
	private void setUpButtons(){
		
		Button setButton = (Button)findViewById(R.id.setAlarmclock);
		setButton.setOnClickListener(new onClick());
		
		Button cancelButton = (Button)findViewById(R.id.cancelAll);
		cancelButton.setOnClickListener(new onClick());
	}
	
	/** Start Alarmsound */
	public static void playAlarmSound(){
		mService.playSound();
				
	}
	
	/** Stop Alarmsound */
	public static void stopAlarmSound(){
		mService.stopSound();
	}
	
	private void alarm(int selectedHour, int selectedMinute){
		int timeDiffrence = getTimeDiffrence(selectedHour, selectedMinute);
		if(timeDiffrence != 0){
			
			// Show user what time the alarm will go off
			alarm.setText(getString(R.string.Alarmsetto)+convertTimeToString(selectedHour)+":"+convertTimeToString(selectedMinute));
			
	        // Schedule the alarm timeDiffrence in seconds
			long startTime = timeDiffrence*1000 + System.currentTimeMillis();
		
			System.out.println("StartTime: "+startTime);
			
	        am.set(AlarmManager.RTC_WAKEUP, startTime, alarmIntent);
	        //setButton.setEnabled(false);
	        setAlarmON(true);
	        
	        if(timeDiffrence < 60){
	        	showToast( "Alarm will go off in about "+timeDiffrence+" seconds." );
	        }
		}
		else {
			int temp = time.minute + 1;
			showToast("Cannot set alarm earlier then "+time.hour+":"+temp);
			
		}
	}
	
	/** Calculates and returns time difference in minutes */
	private int getTimeDiffrence(int hours, int minutes){
		int timeDiffrence;
		if( !compareTime(hours, minutes) ){
			return timeDiffrence = 0;
		}
		else{
			timeDiffrence = (((hours - time.hour)*3600) + ((minutes - time.minute)*60)-time.second); // Calculate the time diffrenece in seconds
			return timeDiffrence;
		}
	}
	
	/** Returns true if compared time in later then 'now' */
	private boolean compareTime(int hours, int minutes){
		if( (hours > time.hour) ){ return true; }
		else if( (hours == time.hour) && (minutes > time.minute) ){
			return true;
		}
		else{
			return false;
		}
	}
	
	private class onClick implements OnClickListener {
		@Override
		public void onClick(View v) {
			if(v.getId() == R.id.setAlarmclock){
				//showToast("set alarmclock");
				
				if( !isAlarmON() ){
					showDialog(TimePicker);
				}
				else{
					showToast("Alarm is already set");
				}
				
			}
			else if(v.getId() == R.id.cancelAll){
				//showToast("Cancel all");

				//stopAlarmSound();
				cancelAlarm();
		
		        // Tell the user about what we did.
		        showToast("Alarm has been unscheduled");	
		        
			}
			else{
				// DO NOTHING
				showToast("No button was click");
				
			}
			
		}
	}
	
	private void cancelAlarm(){

		//setButton.setEnabled(true);
		setAlarmON(false);
        am.cancel(alarmIntent);
        alarm.setText(getString(R.string.Alarmsetto));
	}
    
    @Override
	protected Dialog onCreateDialog(int id) {
		return new TimePickerDialog(this, timePickerListener, time.hour, time.minute,true);
	}
 
	private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int selectedHour, int selectedMinute) {
 			
			alarm(selectedHour, selectedMinute); // set the alarm to the diffrence between current time and selected time in timepicker
 			 			
 		}
	};
	
	private String convertTimeToString(int time){
		if(time >= 10) 
			return ""+time;
		else 
			return "0"+time;
	}
		       
    private void StartClock(){ 
    	// Start up the work thread updating numbers. 
    	keepCounting = true;
    	Thread thr = new Thread(null, count_work, "Clock");
    	thr.start();
    	
    }
    
    private void getCurrentTime(){
    	time.setToNow();
    	hour = time.hour;
    	minutes = time.minute;
    	seconds = time.second;
    }
      
    private String timeToString(){
    	getCurrentTime();
    	String hourtxt, minutestxt, secondstxt;
    	if(hour < 10 ){ hourtxt = "0"+hour;	} else { hourtxt = ""+hour; }
    	if(minutes < 10 ){ minutestxt = "0"+minutes;	} else { minutestxt = ""+minutes; }
    	if(seconds < 10 ){ secondstxt = "0"+seconds;	} else { secondstxt = ""+seconds; }
    	
    	return hourtxt+":"+minutestxt+":"+secondstxt;
    }
  	
    Runnable count_work = new Runnable() {
        public void run() {
        	 while (keepCounting) {    		
        		
            	handler.post(clock_display_update);  // Post message to GUI thread queue
             	SystemClock.sleep(5000);   // Sleep 5 seconds
            }
        }
    };
 
    Runnable clock_display_update = new Runnable() {
        public void run() {  
        	//System.out.println(timeToString());
            clock_display.setText(timeToString());
        }
    };
    
    private void StopClock()  {   	
    	keepCounting = false;        // Force thread to stop working
    }

	/** Defines callbacks for service binding, passed to bindService() */
    private ServiceConnection mConnection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName className, IBinder service) {
            // We've bound to AlarmService, cast the IBinder and get AlarmService instance
			AlarmBinder binder = (AlarmBinder) service;
            mService = binder.getService();
            
			Intent alarm = new Intent();
			alarm.setClass(main_activity,AlarmService.class);
			startService(alarm);
		}
		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			
		}
    };

    /* Diagnostics while developing */
   
    private void showToast(String msg) {
    	Toast.makeText(this,msg,Toast.LENGTH_SHORT).show();
    }

	public static boolean isAlarmON() {
		return alarmON;
	}

	public static void setAlarmON(boolean alarmON) {
		AlarmClock.alarmON = alarmON;
	}
}
